package com.whl.sm.controller.system;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.whl.sm.common.result.Result;
import com.whl.sm.controller.BaseController;
import com.whl.sm.dto.SysMenuDto;
import com.whl.sm.dto.TransferDto;
import com.whl.sm.model.repair.RepairTask;
import com.whl.sm.model.system.OrgUser;
import com.whl.sm.model.system.OrgUserInfo;
import com.whl.sm.model.system.Role;
import com.whl.sm.model.system.UserCpRole;
import com.whl.sm.service.repair.RepairTaskService;
import com.whl.sm.service.system.OrgUserInfoService;
import com.whl.sm.service.system.OrgUserService;
import com.whl.sm.service.system.RoleService;
import com.whl.sm.service.system.UserCpRoleService;
import com.whl.sm.vo.OrgUserInfoRoleVo;
import com.whl.sm.vo.OrgUserInfoVo;
import com.whl.sm.vo.OrgUserRoleVo;
import com.whl.sm.vo.RoleOfServiceVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;


/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author wuhaolun
 * @since 2021-09-10
 */
@RestController
@RequestMapping("/user-cp-role")
public class UserCpRoleController extends BaseController {

    @Autowired
    private UserCpRoleService userCpRoleService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private OrgUserService orgUserService;

    @Autowired
    private OrgUserInfoService orgUserInfoService;

    @Lazy
    @Autowired
    private RepairTaskService repairTaskService;

    @RequestMapping("/user-menu/tree")
    public Result userMenuTree(String userId){
        userId = orgUserService.getCurrentUserId();
        if (Objects.isNull(userId)){
            return Result.build(401,"请进行登录");
        }
        List<SysMenuDto> menuTree =  userCpRoleService.getUserMenuTree(userId);
        Map<String,Object> result = new HashMap<>();
        result.put("nav",menuTree);
        return Result.ok(result);
    }

    @RequestMapping("/user-mag/list")
    public Result magUsers(){
        List<TransferDto> magList =  userCpRoleService.getComMagUserList();
        return Result.ok(magList);
    }


    /**
     * roleType:1(业主,住户)
     * roleType:2(租户)
    * */
    @RequestMapping("/getUserByType")
    public Result getUserByType(HttpServletRequest request){
        Page<Object> userList = new Page<>();
        String likeName = request.getParameter("likeName");
        if (likeName.equals("undefined") || likeName.equals("")){
            return Result.ok(userList);
        }
        QueryWrapper roleQueryWrapper = new QueryWrapper();
        String roleType = request.getParameter("roleType");
        List<Role> roleList = new ArrayList<>();
        List<UserCpRole> userCpRoleList = new ArrayList<>();

        if (StringUtils.isNotBlank(roleType) && roleType.equals("1")){
            roleQueryWrapper.eq("role_name","小区业主");
            roleQueryWrapper.or();
            roleQueryWrapper.eq("role_name","小区住户");
            roleList = roleService.list(roleQueryWrapper);
        }
        else if(StringUtils.isNotBlank(roleType) && roleType.equals("2")){
            roleQueryWrapper.eq("role_name","小区租户");
            roleList = roleService.list(roleQueryWrapper);
        }
        if (roleList.size()>0){
            userCpRoleList = userCpRoleService.list(new QueryWrapper<UserCpRole>()
                    .in("role_id",roleList.stream().map(Role::getId).collect(Collectors.toList()))
            );
        }
        if (userCpRoleList.size()>0){
            QueryWrapper queryWrapper = getLikeParam("user_name");
            queryWrapper.in("user_id",userCpRoleList.stream().map(UserCpRole::getUserId).collect(Collectors.toList()));
            userList = orgUserInfoService.page(getPage(),queryWrapper);
            List<Object> result = userList.getRecords().stream().map(obj->{
                OrgUserInfo orgUserInfo = (OrgUserInfo) obj;
                UserCpRole ucr = userCpRoleService.getOne(new QueryWrapper<UserCpRole>().eq("user_id",orgUserInfo.getUserId()));
                Role role = roleService.getById(ucr.getRoleId());
                return new OrgUserInfoRoleVo(orgUserInfo,role);
            }
            ).collect(Collectors.toList());
            userList.setRecords(result);
        }
        return Result.ok(userList);
    }


    @RequestMapping("/serviceList")
    public Result repairServiceList(HttpServletRequest request){
        QueryWrapper queryWrapper = getLikeParam("user_name");
        Role serviceRole = roleService.getOne(new QueryWrapper<Role>().eq("role_name","维修人员"));
        List<UserCpRole> serviceCpList = userCpRoleService.list(new QueryWrapper<UserCpRole>().eq("role_id",serviceRole.getId()));
        List<String> serviceIdList = serviceCpList.stream().map(UserCpRole::getUserId).collect(Collectors.toList());
        Page<Object> resultPage = new Page();
        String likeName = request.getParameter("likeName");
        if (Objects.isNull(likeName) || likeName.equals("undefined") || likeName.equals("")){
            resultPage = orgUserInfoService.page(getPage(),new QueryWrapper<OrgUserInfo>()
                    .in("user_id",serviceIdList)
            );

        }else {
            queryWrapper.in("user_id",serviceIdList);
            resultPage = orgUserInfoService.page(getPage(),queryWrapper);
        }
        List<Object> resultList = resultPage.getRecords().stream().map(obj->{
            OrgUserInfo object = (OrgUserInfo) obj;
            Integer taskCount = repairTaskService.count(new QueryWrapper<RepairTask>().eq("staff_id",object.getUserId()));
            return new RoleOfServiceVo(object,taskCount);
        }).collect(Collectors.toList());
        resultPage.setRecords(resultList);

        return Result.ok(resultPage);
    }

    @RequestMapping("/getByCurrent")
    public Result getBuCurrent(){
        String userId = orgUserService.getCurrentUserId();
        return userCpRoleService.getByCurrent(userId);
    }


}
